<template>
  <div class="search-suggestions">
    <!-- 联想建议 -->
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <!-- 处理高亮 -->
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search";
import { debounce } from "lodash";

export default {
  name: "SearchSuggestion",
  props: {
    searchText: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      suggestions: [],
    };
  },
  watch: {
    searchText: {
      // handler 完整写法
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value);
      }, 200),
      // handler(value) {
      //   // 调用监听
      //   this.loadSearchSuggestions(value);
      // },
      immediate: true,
    },
  },
  methods: {
    // 获取 联想的 数据
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        this.suggestions = data.data.options;
      } catch (err) {
        this.$toast("数据获取失败，请稍后重试");
      }
    },
    highlight(text) {
      // 如果获取的数据为 空 就不执行
      if (!text) {
        return;
      }
      const highLightStr = `<span style="color:#3296fa">${this.searchText}</span>`;
      // 第一个参数为 要替换的对象 第二个参数 i 忽略大小写 g 全局替换
      const reg = new RegExp(this.searchText, "ig");
      // 数组的 replace 替换方法
      return text.replace(reg, highLightStr);
    },
  },
};
</script>

<style></style>
